﻿using Autofac.Extensions.DependencyInjection;
using Autofac;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoRegister;
using Serilog;
using AutoRegistDependency.Extensions;
using Serilog.Events;
using Serilog.Exceptions;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;

namespace Core
{
    public class Program
    {
        private static IHost? AppHost;
        public static IHost CreateHost(string[] args)
        {
            if(AppHost == null)
            {
                var builder = Host.CreateDefaultBuilder(args);
                builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
                builder.ConfigureContainer<ContainerBuilder>((hostBuilderContext, containerBuilder) =>
                {
                    containerBuilder.RegisterModule(new Register(hostBuilderContext));
                });
                builder.ConfigureServices(service =>
                {
                    service.AddSerilog(lc =>
                    {
                        lc.MinimumLevel.Information()
                        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                        .Enrich.FromLogContext()
                        .Enrich.WithProcessId()
                        .Enrich.WithThreadId()
                        .Enrich.WithExceptionDetails()
                        .Enrich.WithEnvironmentUserName()
                        .WriteTo.Console()
                        .WriteTo.File(Path.Combine("logs", @"log.txt"), restrictedToMinimumLevel: LogEventLevel.Information, rollingInterval: RollingInterval.Day);
                    });
                    service.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
                });
                var host = builder.Build();
                host.Services.QuartzRegist();
                AppHost = host;
            }
            return AppHost;
        }

        public static T GetService<T>() where T : class
        {
            var context = AppHost?.Services.GetService<IComponentContext>();
            return context!.Resolve<T>();
        }
        public static object GetService(Type serviceType)
        {
            IComponentContext context = AppHost.Services.GetService<IComponentContext>()!;
            return context.Resolve(serviceType);
        }
    }
}
